package com.doublefish.doublefishrobot.ui.home.s6;

import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.base.BaseActivity;
import com.doublefish.doublefishrobot.ui.home.bean.ModeSettingBean;
import com.doublefish.doublefishrobot.ui.home.path.DFPingPongTableView;
import com.doublefish.doublefishrobot.ui.home.widget.ModeSettingItemNormalContentView;
import com.doublefish.doublefishrobot.ui.home.widget.ModeSettingItemValuePopView;
import com.doublefish.doublefishrobot.ui.home.widget.SafeDialog;
import com.doublefish.doublefishrobot.utils.DebounceOnClickListener;
import com.doublefish.doublefishrobot.utils.ble.DFBleManager;
import com.doublefish.doublefishrobot.utils.ble.DFS6ProtocolManager;
import com.doublefish.doublefishrobot.utils.ble.bean.ModeConstant;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者:dugaofeng on 2024/10/24 10:13
 */
public class S6ModeNormalActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView titleTV;

    @BindView(R.id.pingpong_view)
    DFPingPongTableView pingPongTableView;

    @BindView(R.id.mode_normal_content)
    ModeSettingItemNormalContentView normalContentView;

    @BindView(R.id.tv_testball)
    TextView testTV;

    @BindView(R.id.tv_train)
    TextView trainTV;

    private int modeId;
    private ModeSettingBean.ModeSettingStepBean stepBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_mode_normal_s6;
    }

    @Override
    protected void initView() {
        titleTV.setText(getString(R.string.basic_mode));
    }

    @Override
    protected void initListener() {
        normalContentView.setOnModeSettingItemNormalContentViewListner(new ModeSettingItemNormalContentView.OnModeSettingItemNormalContentViewListner() {
            @Override
            public void onModeSettingItemValueClick(ModeSettingBean.ModeSettingStepBean stepBean, ModeSettingBean.ModeSettingItemBean itemBean, ModeSettingBean.ModeSettingItemTag itemTag) {
                showItemValuePopView(stepBean ,itemBean, itemTag);
            }
        });

        testTV.setOnClickListener(new DebounceOnClickListener() {
            @Override
            protected void onClickView(View view) {
                testBallBtnClick();
            }
        });
        trainTV.setOnClickListener(new DebounceOnClickListener() {
            @Override
            protected void onClickView(View view) {
                trainBtnClick();
            }
        });
    }

    @Override
    protected void initData() {
        String json = readModeSettingFromFile();
        ModeSettingBean settingBean = JSON.parseObject(json, ModeSettingBean.class);
        if (settingBean == null) {
            return;
        }
        settingBean.setProtocolType(ModeConstant.ProtocolTypeS6);
        if (settingBean.getSteps() == null || settingBean.getSteps().size() == 0) {
            return;
        }
        //基本模式取第一个
        modeId = settingBean.getMode();
        stepBean = settingBean.getSteps().get(0);
        //基本模式 与其他模式相比，比较特殊，第一个字段不是单球次数，而是循环配置，所以这里要单独处理下
        ModeSettingBean.ModeSettingLoopBean loopBean = ModeSettingBean.ModeSettingLoopBean.defaultLoop(ModeConstant.ProtocolTypeS6);;
        stepBean.setLoopCountItemBean(loopBean.getLoopCountItemBean());
        stepBean.setLoopTimeItemBean(loopBean.getLoopTimeItemBean());
        stepBean.setLoopIntervalItemBean(loopBean.getLoopIntervalItemBean());

        //只有基本模式 修改最大频率为90
        ModeSettingBean.ModeSettingItemBean frequencyItemBean = stepBean.getFrequencyItemBean();
        frequencyItemBean.setMaxValue(90);
        frequencyItemBean.setCurrentMaxValue(90);

        reloadData();
    }

    @OnClick(R.id.ll_back)
    public void onBackClick() {
        finish();
    }

    private void reloadData() {
        normalContentView.setSettingStepBean(stepBean);
        pingPongTableView.setS6StepBean(stepBean);
    }

    //从本地Assets中读取文件
    private String readModeSettingFromFile() {
        try {
            String fileName = null;
            if (DFBleManager.getInstance().curDeviceIsProtocolTypeS6()) {
                fileName = "s6_mode_normal.json";
            }
            if (fileName == null) {
                showToast(getString(R.string.fail_get_basic_param));
                return null;
            }
            InputStream inputStream = getResources().getAssets().open(fileName);
            int length = inputStream.available();
            byte[] buff = new byte[length];
            inputStream.read(buff);
            inputStream.close();

            String json = new String(buff, StandardCharsets.UTF_8);
            return json;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void showItemValuePopView(ModeSettingBean.ModeSettingStepBean stepBean, ModeSettingBean.ModeSettingItemBean itemBean, ModeSettingBean.ModeSettingItemTag itemTag) {
        if (itemTag == ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagLoopCount
                || itemTag == ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagLoopTime) {
            List<ModeSettingBean.ModeSettingItemBean> itemBeans = new ArrayList<>();
            itemBeans.add(stepBean.getLoopCountItemBean());
            itemBeans.add(stepBean.getLoopTimeItemBean());

            List<String> itemMsgs = new ArrayList<>();
            itemMsgs.add(stepBean.getLoopCountItemBean().getDescWithItemTag(ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagLoopCount));
            itemMsgs.add(stepBean.getLoopTimeItemBean().getDescWithItemTag(ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagLoopTime));

            int index = itemTag == ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagLoopCount ? 0 : 1;
            ModeSettingItemValuePopView popView = new ModeSettingItemValuePopView(this, itemBeans, itemMsgs, index, new ModeSettingItemValuePopView.OnSettingItemValuePopViewListner() {
                @Override
                public void onValueFinish(ModeSettingBean.ModeSettingItemBean itemBean, int index) {
                    stepBean.setLoopType(index);
                    reloadData();
                }

                @Override
                public void onValueError(String error) {
                    showToast(error);
                }

                @Override
                public void onCancelBtnClick() {

                }
            });
            popView.show();

        } else if (itemTag == ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagNoRotation
                || itemTag == ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagUpRotation
                || itemTag == ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagDownRotation) {
            List<ModeSettingBean.ModeSettingItemBean> itemBeans = new ArrayList<>();
            itemBeans.add(stepBean.getUpRotationItemBean());
            itemBeans.add(stepBean.getNoRotationItemBean());
            itemBeans.add(stepBean.getDownRotationItemBean());

            List<String> itemMsgs = new ArrayList<>();
            itemMsgs.add(stepBean.getUpRotationItemBean().getDescWithItemTag(ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagUpRotation));
            itemMsgs.add(stepBean.getNoRotationItemBean().getDescWithItemTag(ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagNoRotation));
            itemMsgs.add(stepBean.getDownRotationItemBean().getDescWithItemTag(ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagDownRotation));

            int index = 0;
            if (itemTag == ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagNoRotation) {
                index = 1;
            } else if (itemTag == ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagDownRotation) {
                index = 2;
            }

            ModeSettingItemValuePopView popView = new ModeSettingItemValuePopView(this, itemBeans, itemMsgs, index, new ModeSettingItemValuePopView.OnSettingItemValuePopViewListner() {
                @Override
                public void onValueFinish(ModeSettingBean.ModeSettingItemBean itemBean, int index) {
                    //0.不旋  1上旋  2下旋
                    int rotationType = 1;
                    if (index == 0) {
                        rotationType = 1;
                    } else if (index == 1) {
                        rotationType = 0;
                    } else if (index == 2) {
                        rotationType = 2;
                    }
                    stepBean.setRotationType(rotationType);
                    reloadData();
                }

                @Override
                public void onValueError(String error) {
                    showToast(error);
                }

                @Override
                public void onCancelBtnClick() {

                }
            });
            popView.show();
        } else {
            String itemMsg = itemBean.getDescWithItemTag(itemTag);
            ModeSettingItemValuePopView popView = new ModeSettingItemValuePopView(this, itemBean, itemMsg, new ModeSettingItemValuePopView.OnSettingItemValuePopViewListner() {
                @Override
                public void onValueFinish(ModeSettingBean.ModeSettingItemBean itemBean, int index) {
                    reloadData();
                }

                @Override
                public void onValueError(String error) {
                    showToast(error);
                }

                @Override
                public void onCancelBtnClick() {

                }
            });
            popView.show();
        }
    }

    private void testBallBtnClick() {
        if (!DFBleManager.getInstance().isDidConnectBlueTooth()) {
            showToast(getString(R.string.connect_ble_first));
            return;
        }
        if (SafeDialog.shouldShowSafeDialog()) {
            boolean isHigSpeed = false;
            if (stepBean.getSpeedItemBean().isChooseRange()) {
                if (stepBean.getSpeedItemBean().getCurrentMaxValue() > SafeDialog.S6_TIPS_MAX_SPEED) {
                    isHigSpeed = true;
                }
            } else {
                if (stepBean.getSpeedItemBean().getCurrentValue() > SafeDialog.S6_TIPS_MAX_SPEED) {
                    isHigSpeed = true;
                }
            }
            if (isHigSpeed) {
                new SafeDialog(this, new SafeDialog.OnDialogListner() {
                    @Override
                    public void onComfirmBtnClick() {
                        startTestBall();
                    }

                    @Override
                    public void onCancelBtnClick() {

                    }
                }).show();
            } else {
                startTestBall();
            }
        } else {
            startTestBall();
        }
    }

    private void startTestBall() {
//        String script = "0,1,#0,40,#0,17,#0,34,#0,38,#0,6,#0,90,#";
        if (DFBleManager.getInstance().curDeviceIsProtocolTypeS6()) {
            String script = stepBean.makeScript();
            DFS6ProtocolManager.getInstance().testBall(script);
        }
    }

    private void trainBtnClick() {
        if (!DFBleManager.getInstance().isDidConnectBlueTooth()) {
            showToast(getString(R.string.connect_ble_first));
            return;
        }
        if (SafeDialog.shouldShowSafeDialog()) {
            boolean isHigSpeed = false;
            if (stepBean.getSpeedItemBean().isChooseRange()) {
                if (stepBean.getSpeedItemBean().getCurrentMaxValue() > SafeDialog.S6_TIPS_MAX_SPEED) {
                    isHigSpeed = true;
                }
            } else {
                if (stepBean.getSpeedItemBean().getCurrentValue() > SafeDialog.S6_TIPS_MAX_SPEED) {
                    isHigSpeed = true;
                }
            }
            if (isHigSpeed) {
                new SafeDialog(this, new SafeDialog.OnDialogListner() {
                    @Override
                    public void onComfirmBtnClick() {
                        startTrain();
                    }

                    @Override
                    public void onCancelBtnClick() {

                    }
                }).show();
            } else {
                startTrain();
            }
        } else {
            startTrain();
        }
    }

    private void startTrain() {
        //运行的时间 次数
        boolean isTime = (stepBean.getLoopType() == 1);
        int count = stepBean.getLoopCountItemBean().getCurrentValue();

        //mark：--  2024-1-4 发球时间 和 发球频率
        //单位 分钟 -> 秒
        int time = stepBean.getLoopTimeItemBean().getCurrentValue() * 60;

        //基本模式的由于没有单球次数，所以都是默认发一个球
        //发球频率其实是 脚本的间隔
        int frequency = stepBean.getFrequencyItemBean().isChooseRange() ? ((stepBean.getFrequencyItemBean().getCurrentMinValue() + stepBean.getFrequencyItemBean().getCurrentMaxValue()) / 2) : stepBean.getFrequencyItemBean().getCurrentValue();
        int loopInterval = 60000 / frequency; //单位ms

        String script = stepBean.makeScript();  //生成脚本

//        Intent intent = new Intent(this, S6ModeBallActivity.class);
//        intent.putExtra("modeId", modeId);
//        intent.putExtra("modeName", "基本模式");
//        intent.putExtra("isSystem", false);
//        intent.putExtra("script", script);
//        intent.putExtra("loopInterval", loopInterval);
//        intent.putExtra("isTime", isTime);
//        intent.putExtra("time", time);
//        intent.putExtra("count", count);
//        startActivity(intent);

        Intent intent = S6ModeBallActivity.createScriptIntent(this,
                getString(R.string.basic_mode),
                false,
                script,
                loopInterval,
                isTime,
                time,
                count);
        startActivity(intent);
    }
}